package com.lh.core.aspect;

import com.lh.entity.table.DsmsUser;
import com.lh.entity.vo.TokenModel;
import com.lh.mapper.DsmsUserMapper;
import com.lh.service.TokenManager;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Component
public class OnlyAdminAop {

    @Autowired
    private TokenManager tokenManager;

    @Resource
    private DsmsUserMapper dsmsUserMapper;

    @Pointcut("@annotation(com.lh.core.annotation.OnlyAdmin)")
    public void onlyAdmin() {
    }

    // 使用正确的切点 onlyAdmin()
    @Before("onlyAdmin()")
    public void doBefore(JoinPoint point) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            throw new RuntimeException("请求头的Authorization为空");
        }
        //验证token
        TokenModel model = tokenManager.getToken(authorization);
        if (model == null) {
            throw new RuntimeException("没登录");

        }
        Long userId = model.getUserId();
        DsmsUser dsmsUser = dsmsUserMapper.selectById(userId);
        if (dsmsUser == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!"admin".equals(dsmsUser.getRoleCode())) {
            throw new RuntimeException("没权限");
        }
    }

}